/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.lucene.index;

import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.BitSetIterator;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.RamUsageEstimator;

/** Accumulator for documents that have a value for a field. This is optimized
 *  for the case that all documents have a value. */
final class DocsWithFieldSet extends DocIdSet {

  private static long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(DocsWithFieldSet.class);

  private FixedBitSet set;
  private int cost = 0;
  // 记录上一次文档号
  private int lastDocId = -1;

  // 用来记录文档号， 当添加的文档号是连续的，那么能提高记录速度
  void add(int docID) {
    if (docID <= lastDocId) {
      throw new IllegalArgumentException("Out of order doc ids: last=" + lastDocId + ", next=" + docID);
    }
    if (set != null) {
      // 说明已经出现过不满足“特殊条件”的情况了（见《Writer相关实例》），所以走FixedBitSet
      set = FixedBitSet.ensureCapacity(set, docID);
      set.set(docID);
    } else if (docID != cost) {
      // 说明从当前处理的文档号开始就不满足“特殊条件”了，此时使用新建的FixedBitSet存储文档号，同时将之前处理的文档号（通过cost的值获得）以及当前文档号存储到新建的FixedBitSet对象中。当然还得继续更新lastDocId，因为在处理下一个文档号时，lastDocId要用于判断文档号是否递增；cost的值依然执行cost++的操作，因为cost的功能不仅仅是用来判断在“特殊条件”下，用来描述存储的文档号集合，它还要用来描述DocsWithFieldSet处理的文档号数量
      set = new FixedBitSet(docID + 1);
      set.set(0, cost);
      set.set(docID);
    }
    // docId等于cost：说明目前仍然处于满足“特殊条件”的情况，那么直接更新lastDocId的值更新为dociId，接着更新cost的值，即cost++的操作，在这个操作之后，目前DocsWithFieldSet已经处理（存储）的文档号集合为[0, cost]
    lastDocId = docID;
    cost++;
  }

  @Override
  public long ramBytesUsed() {
    return BASE_RAM_BYTES_USED + (set == null ? 0 : set.ramBytesUsed());
  }

  @Override
  public DocIdSetIterator iterator() {
    return set != null ? new BitSetIterator(set, cost) : DocIdSetIterator.all(cost);
  }

}
